<template>
  <view class="container">
    <!-- 地图区域 -->
    <view class="map-container">
      <map
        id="map"
        class="map"
        :latitude="latitude"
        :longitude="longitude"
        :markers="markers"
        :scale="14"
        :show-location="isShowLocation"
        @markertap="handleMarkerTap"
        :enable-rotate="true"
        :enable-zoom="true"
        :enable-scroll="true"
        :enable-3D="true"
        :show-compass="true"
        :show-scale="true"
      ></map>
      <!-- 地图控制按钮 -->
      <view class="map-controls">
        <button class="control-btn" @click="handleLocation">
          <image class="icon" src="/static/icons/location.svg" mode="aspectFit"></image>
        </button>
        <button class="control-btn" @click="handleZoomIn">
          <image class="icon" src="/static/icons/plus.svg" mode="aspectFit"></image>
        </button>
        <button class="control-btn" @click="handleZoomOut">
          <image class="icon" src="/static/icons/minus.svg" mode="aspectFit"></image>
        </button>
      </view>
    </view>

    <!-- 门店列表 -->
    <view class="store-list" :class="{ 'store-list-expanded': isListExpanded }">
      <view class="list-header">
        <view class="search-box">
          <input
            type="text"
            v-model="searchKeyword"
            placeholder="搜索附近门店"
            class="search-input"
          />
          <button class="search-btn" @click="handleSearch">
            <image class="search-icon" src="/static/icons/search.svg" mode="aspectFit"></image>
            搜索
          </button>
        </view>
        <view class="list-toggle" @click="toggleList">
          <image class="toggle-icon" :src="isListExpanded ? '/static/icons/down.svg' : '/static/icons/up.svg'" mode="aspectFit"></image>
        </view>
      </view>

      <scroll-view scroll-y class="store-scroll">
        <view
          v-for="store in storeList"
          :key="store.deviceId"
          class="store-item"
          @click="handleStoreClick(store)"
        >
          <view class="store-info">
            <text class="store-name">{{ store.deviceName }}</text>
            <text class="store-no">设备编号：{{ store.deviceNo }}</text>
            <text class="store-model">型号：{{ store.model }}</text>
            <view class="store-meta">
              <view class="meta-item">
                <image 
                  class="meta-icon" 
                  src="/static/icons/distance.svg" 
                  mode="aspectFit"
                  @error="handleIconError"
                ></image>
                <text class="store-distance">{{ store.distance }}km</text>
              </view>
              <view class="meta-item">
                <image 
                  class="meta-icon" 
                  src="/static/icons/channel.svg" 
                  mode="aspectFit"
                  @error="handleIconError"
                ></image>
                <text class="store-channels">通道数：{{ store.channelCount }}</text>
              </view>
              <view class="meta-item">
                <image 
                  class="meta-icon" 
                  :src="getStatusIcon(store.status)" 
                  mode="aspectFit"
                  @error="handleIconError"
                  @load="handleIconLoad"
                ></image>
                <text
                  class="store-status"
                  :class="getStatusClass(store.status)"
                >
                  {{ getStatusText(store.status) }}
                </text>
              </view>
            </view>
          </view>
          <view class="store-actions">
            <button class="action-btn" @click.stop="handleNavigate(store)">
              <image class="action-icon" src="/static/icons/navigate-block.svg" mode="aspectFit"></image>
              导航
            </button>
          </view>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import * as mapApi from '@/api/map';
import { getDeviceDetail } from '@/api/device';
import type { DeviceVO } from '@/api/device/types';

// 地图中心点
const latitude = ref(30.572815);
const longitude = ref(104.066803);

// 是否显示当前位置
const isShowLocation = ref(true);

// 搜索关键词
const searchKeyword = ref("");

// 列表展开状态
const isListExpanded = ref(false);

// 地图标记点
const markers = ref([]);

// 门店列表数据
const storeList = ref<any[]>([]);

// 计算两点之间的距离（使用高德地图的距离计算）
const calculateDistance = (lat1: number, lon1: number, lat2: number, lon2: number) => {
  if (!lat1 || !lon1 || !lat2 || !lon2) {
    console.log('距离计算参数无效：', { lat1, lon1, lat2, lon2 });
    return 0;
  }
  
  const R = 6378137; // 地球半径，单位米
  const dLat = (lat2 - lat1) * Math.PI / 180;
  const dLon = (lon2 - lon1) * Math.PI / 180;
  const a = Math.sin(dLat/2) * Math.sin(dLat/2) +
    Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * 
    Math.sin(dLon/2) * Math.sin(dLon/2);
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
  const distance = R * c;
  
  // 转换为公里，保留一位小数
  const distanceInKm = Number((distance / 1000).toFixed(1));
  console.log('距离计算结果：', {
    from: { lat: lat1, lon: lon1 },
    to: { lat: lat2, lon: lon2 },
    distance: distanceInKm
  });
  return distanceInKm;
};

// 检查位置权限
const checkLocationPermission = () => {
  return new Promise((resolve, reject) => {
    uni.authorize({
      scope: 'scope.userLocation',
      success: () => {
        resolve(true);
      },
      fail: () => {
        uni.showModal({
          title: '提示',
          content: '需要获取您的位置信息，是否授权？',
          success: (res) => {
            if (res.confirm) {
              uni.openSetting({
                success: (settingRes) => {
                  if (settingRes.authSetting['scope.userLocation']) {
                    resolve(true);
                  } else {
                    reject(new Error('用户拒绝授权位置信息'));
                  }
                },
                fail: () => {
                  reject(new Error('打开设置页面失败'));
                }
              });
            } else {
              reject(new Error('用户拒绝授权位置信息'));
            }
          }
        });
      }
    });
  });
};

// 获取设备详情
const getDeviceInfo = async (deviceId: number) => {
  try {
    const result = await getDeviceDetail(deviceId, 1);
    if (result.data) {
      return result.data;
    }
    return null;
  } catch (error) {
    console.error('获取设备详情失败：', error);
    return null;
  }
};

// 获取当前位置
const getCurrentLocation = async () => {
  try {
    // 先检查权限
    await checkLocationPermission();
    
    // 显示加载提示
    uni.showLoading({
      title: '定位中...'
    });

    uni.getLocation({
      type: "gcj02",
      success: async (res) => {
        latitude.value = res.latitude;
        longitude.value = res.longitude;
        
        // 更新地图中心点
        const mapContext = uni.createMapContext("map");
        
        // 获取周边门店
        try {
          const result = await mapApi.searchAround(res.longitude, res.latitude, '', 5);
          if (result.data) {
            // 获取每个设备的详细信息
            const deviceDetails = await Promise.all(
              result.data.map(async (device) => {
                const detail = await getDeviceInfo(device.deviceId);
                return {
                  ...device,
                  ...detail
                };
              })
            );

            storeList.value = deviceDetails.map((device) => {
              const deviceLat = Number(device.location?.latitude || device.location?.lat);
              const deviceLon = Number(device.location?.longitude || device.location?.lon);
              
              console.log('设备位置：', {
                deviceId: device.deviceId,
                latitude: deviceLat,
                longitude: deviceLon
              });

              // 计算距离
              const distance = calculateDistance(
                latitude.value,
                longitude.value,
                deviceLat,
                deviceLon
              );

              return {
                deviceId: device.id,
                deviceName: device.deviceName || '自助售货机',
                deviceNo: device.deviceNo || '',
                model: device.model || '',
                status: device.status || 1,
                channelCount: device.channelCount || 0,
                distance: distance,
                location: {
                  ...device.location,
                  latitude: deviceLat,
                  longitude: deviceLon
                },
                createTime: device.createTime,
                updateTime: device.updateTime
              };
            });
            // 更新地图标记
            markers.value = storeList.value.map(store => ({
              id: store.deviceId,
              latitude: store.location.latitude,
              longitude: store.location.longitude,
              title: store.deviceName,
              iconPath: "/static/marker.png",
              width: 32,
              height: 42,
              callout: {
                content: `${store.deviceName}\n${getStatusText(store.status)}`,
                color: "#000000",
                fontSize: 14,
                borderRadius: 4,
                bgColor: "#ffffff",
                padding: 8,
                display: "ALWAYS",
              },
            }));
          }
        } catch (error) {
          console.error('获取周边门店失败：', error);
          uni.showToast({
            title: "获取门店信息失败",
            icon: "error",
          });
        }
      },
      fail: (error) => {
        console.error('获取位置失败：', error);
        uni.showToast({
          title: "获取位置失败，请检查定位权限",
          icon: "error",
          duration: 2000
        });
      },
      complete: () => {
        uni.hideLoading();
      }
    });
  } catch (error) {
    console.error('位置权限检查失败：', error);
    uni.showToast({
      title: error.message || "获取位置失败",
      icon: "error",
      duration: 2000
    });
  }
};

// 处理标记点点击
const handleMarkerTap = (e: any) => {
  const marker = markers.value.find((m) => m.id === e.markerId);
  if (marker) {
    const store = storeList.value.find(s => s.deviceId === marker.id);
    if (store) {
      handleStoreClick(store);
    }
  }
};

// 处理门店点击
const handleStoreClick = (store: any) => {
  // 移动地图到选中的门店位置
  const mapContext = uni.createMapContext("map");
  mapContext.moveToLocation({
    latitude: store.location.lat,
    longitude: store.location.lon,
  });

  // 跳转到设备详情页面
  uni.navigateTo({
    url: `/pages/device/detail?id=${store.deviceId}`,
    fail: (error) => {
      console.error('跳转失败：', error);
      uni.showToast({
        title: '跳转失败',
        icon: 'error'
      });
    }
  });
};

// 处理导航
const handleNavigate = (store: any) => {
	console.log(store)
  // 然后跳转到导航页面
  uni.navigateTo({
    url: `/pages/device/navigate?id=${store.deviceId}`
  });
};

// 处理搜索
const handleSearch = async () => {
  if (!searchKeyword.value.trim()) {
    uni.showToast({
      title: '请输入搜索关键词',
      icon: 'none'
    });
    return;
  }

  try {
    uni.showLoading({
      title: '搜索中...'
    });

    // 暂时关闭当前位置显示
    isShowLocation.value = false;

    // 使用 geocode 获取地址的经纬度
    const geocodeResult = await mapApi.geocode(searchKeyword.value);
    // console.log(geocodeResult);
    if (geocodeResult.data && geocodeResult.data.latitude && geocodeResult.data.longitude) {
      const { latitude: newLatitude, longitude: newLongitude } = geocodeResult.data;

      // 更新地图中心点
      latitude.value = newLatitude;
      longitude.value = newLongitude;
      
      // 移动地图到搜索位置
      const mapContext = uni.createMapContext("map");

      // 搜索周边门店
      const result = await mapApi.searchAround(newLongitude, newLatitude, '', 5);
      if (result.data) {
        // 获取每个设备的详细信息
        const deviceDetails = await Promise.all(
          result.data.map(async (device) => {
            const detail = await getDeviceInfo(device.deviceId);
            return {
              ...device,
              ...detail
            };
          })
        );

        storeList.value = deviceDetails.map((device) => {
          const deviceLat = Number(device.location?.latitude || device.location?.lat);
          const deviceLon = Number(device.location?.longitude || device.location?.lon);
          
          // 计算距离
          const distance = calculateDistance(
            latitude.value,
            longitude.value,
            deviceLat,
            deviceLon
          );

          return {
            deviceId: device.id,
            deviceName: device.deviceName || '自助售货机',
            deviceNo: device.deviceNo || '',
            model: device.model || '',
            status: device.status || 1,
            channelCount: device.channelCount || 0,
            distance: distance,
            location: {
              ...device.location,
              latitude: deviceLat,
              longitude: deviceLon
            },
            createTime: device.createTime,
            updateTime: device.updateTime
          };
        });
        
        // 更新地图标记
        markers.value = storeList.value.map(store => ({
          id: store.deviceId,
          latitude: store.location.lat,
          longitude: store.location.lon,
          title: store.deviceName,
          iconPath: "/static/marker.png",
          width: 32,
          height: 32,
          callout: {
            content: `${store.deviceName}\n${getStatusText(store.status)}`,
            color: "#000000",
            fontSize: 14,
            borderRadius: 4,
            bgColor: "#ffffff",
            padding: 8,
            display: "ALWAYS",
          },
        }));

        // 展开列表
        isListExpanded.value = true;
      }
    } else {
      uni.showToast({
        title: '未找到相关位置',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('搜索失败：', error);
    uni.showToast({
      title: '搜索失败，请重试',
      icon: 'none'
    });
  } finally {
    uni.hideLoading();
  }
};

// 切换列表展开状态
const toggleList = () => {
  isListExpanded.value = !isListExpanded.value;
};

// 处理定位按钮点击
const handleLocation = async () => {
  try {
    // 显示加载提示
    uni.showLoading({
      title: '定位中...'
    });

    // 开启当前位置显示
    isShowLocation.value = true;

    // 获取当前位置
    await getCurrentLocation();
  } catch (error) {
    console.error('定位失败：', error);
    uni.showToast({
      title: '定位失败，请重试',
      icon: 'none'
    });
  } finally {
    uni.hideLoading();
  }
};

const handleZoomIn = () => {
  const mapContext = uni.createMapContext("map");
  mapContext.includePoints({
    points: markers.value.map(marker => ({
      latitude: marker.latitude,
      longitude: marker.longitude
    })),
    padding: [50, 50, 50, 50]
  });
};

const handleZoomOut = () => {
  const mapContext = uni.createMapContext("map");
  mapContext.includePoints({
    points: markers.value.map(marker => ({
      latitude: marker.latitude,
      longitude: marker.longitude
    })),
    padding: [100, 100, 100, 100]
  });
};

// 获取状态图标
const getStatusIcon = (status: number) => {
  let iconPath = '/static/icons/offline.svg'; // 默认图标
  
  switch (status) {
    case 2: // 在线
      iconPath = '/static/icons/online.svg';
      break;
    case 1: // 离线
      iconPath = '/static/icons/offline.svg';
      break;
    case 3: // 故障
    case 4: // 维护中
    case 5: // 待维护
      iconPath = '/static/icons/maintenance.svg';
      break;
    default: // 未使用或其他状态
      iconPath = '/static/icons/offline.svg';
      break;
  }
  
  return iconPath;
};

// 获取状态文本
const getStatusText = (status: number) => {
  switch (status) {
    case 0:
      return '未使用';
    case 1:
      return '离线';
    case 2:
      return '在线';
    case 3:
      return '故障';
    case 4:
      return '维护中';
    case 5:
      return '待维护';
    default:
      return '未知';
  }
};

// 获取状态样式类
const getStatusClass = (status: number) => {
  switch (status) {
    case 2: // 在线
      return 'status-online';
    case 1: // 离线
      return 'status-offline';
    case 3: // 故障
      return 'status-error';
    case 4: // 维护中
    case 5: // 待维护
      return 'status-maintenance';
    default: // 未使用
      return 'status-offline';
  }
};

// 判断设备是否可用
const isDeviceAvailable = (status: number) => {
  return status === 2; // 只有在线状态才可用
};

// 页面加载时获取位置
onMounted(() => {
  getCurrentLocation();
});

</script>

<style>
.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f5f5;
  position: relative;
}

.map-container {
  width: 100%;
  height: 100%;
  position: relative;
}

.map {
  width: 100%;
  height: 100%;
}

.map-controls {
  position: absolute;
  right: 30rpx;
  bottom: 20%;
  display: flex;
  flex-direction: column;
  gap: 20rpx;
  z-index: 100;
}

.control-btn {
  width: 88rpx;
  height: 88rpx;
  background-color: #ffffff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
  padding: 0;
  margin: 0;
  line-height: 1;
}

.control-btn:active {
  background-color: #f0f0f0;
}

.store-list {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #ffffff;
  border-radius: 30rpx 30rpx 0 0;
  padding: 30rpx;
  box-shadow: 0 -4rpx 16rpx rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  transform: translateY(75%);
  z-index: 99;
  height: 75vh;
}

.store-list-expanded {
  transform: translateY(0);
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
  padding-bottom: 20rpx;
  border-bottom: 1px solid #f0f0f0;
}

.search-box {
  flex: 1;
  display: flex;
  gap: 20rpx;
  margin-right: 20rpx;
}

.search-input {
  flex: 1;
  height: 80rpx;
  background-color: #f5f5f5;
  border-radius: 40rpx;
  padding: 0 40rpx;
  font-size: 28rpx;
}

.search-btn {
  width: 140rpx;
  height: 80rpx;
  background-color: #007aff;
  color: #ffffff;
  border-radius: 40rpx;
  font-size: 28rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0;
  margin: 0;
  line-height: 1;
}

.search-btn:active {
  background-color: #0062cc;
}

.list-toggle {
  padding: 12rpx 24rpx;
  background-color: #f5f5f5;
  border-radius: 30rpx;
}

.toggle-icon {
  font-size: 24rpx;
  color: #666;
}

.store-scroll {
  height: calc(100% - 130rpx);
}

.store-item {
  display: flex;
  justify-content: space-between;
  padding: 30rpx 0;
  border-bottom: 1px solid #f0f0f0;
}

.store-info {
  flex: 1;
  margin-right: 30rpx;
}

.store-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 12rpx;
  display: block;
}

.store-no {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 8rpx;
  display: block;
}

.store-model {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 12rpx;
  display: block;
}

.store-channels {
  font-size: 24rpx;
  color: #666;
  background-color: #f5f5f5;
  padding: 4rpx 12rpx;
  border-radius: 20rpx;
}

.store-meta {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.store-distance {
  font-size: 24rpx;
  color: #999;
  background-color: #f5f5f5;
  padding: 4rpx 12rpx;
  border-radius: 20rpx;
}

.store-status {
  font-size: 24rpx;
  padding: 4rpx 12rpx;
  border-radius: 20rpx;
}

.status-online {
  color: #52c41a;
  background-color: #f6ffed;
}

.status-offline {
  color: #999999;
  background-color: #f5f5f5;
}

.status-error {
  color: #ff4d4f;
  background-color: #fff1f0;
}

.status-maintenance {
  color: #faad14;
  background-color: #fffbe6;
}

.store-actions {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.action-btn {
  width: 120rpx;
  height: 60rpx;
  font-size: 24rpx;
  padding: 0;
  margin: 0;
  line-height: 60rpx;
  background-color: #f5f5f5;
  color: #666;
  border-radius: 30rpx;
}

.action-btn:active {
  background-color: #e8e8e8;
}

.icon {
  width: 40rpx;
  height: 40rpx;
}

.search-icon {
  width: 32rpx;
  height: 32rpx;
  margin-right: 8rpx;
}

.toggle-icon {
  width: 32rpx;
  height: 32rpx;
}

.meta-icon {
  width: 28rpx;
  height: 28rpx;
  margin-right: 4rpx;
}

.action-icon {
  width: 28rpx;
  height: 28rpx;
  margin-right: 4rpx;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 4rpx;
}

.search-btn {
  display: flex;
  align-items: center;
  justify-content: center;
}

.action-btn {
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
